package com.douyu.data.up.util;

import com.alibaba.fastjson.JSONPath;
import com.douyu.data.common.Constant;
import com.douyu.data.common.util.NetUtil;
import com.douyu.data.up.entity.Up;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;

import java.io.IOException;
import java.net.URL;
import java.util.StringJoiner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UpDetailFromDouYu {

    public static Up request(String url, String id) throws IOException, JSONException {
        String fullUrl = url + id;
        Up up = new Up();
        Document parse = Jsoup.parse(new URL(fullUrl), 20000);
        up.setId(id);
        // 1.名称
        up.setName(getElementsByClassForText(parse,"Title-anchorNameH2"));
        // 2.等级
        up.setLevel(getElementsByClassForAttr(parse,"AnchorLevel", "class")
                .replaceAll("[^0-9]",""));
        // 3.公会
        up.setAssociation(getElementsByClassForAttr(parse,"SociatyLabel", "title")
                .replace("公会：", ""));
        // 4.分区
        String partitionUrl = "";
        StringJoiner joiner= new StringJoiner(">");
        for (Element elementsByClass : getElementsByClass(parse, "Title-categoryItem")) {
            if(StringUtils.isNotBlank(elementsByClass.text())){
                joiner.add(elementsByClass.text());
                partitionUrl = elementsByClass.attr("href");
            }
        }
        up.setPartitionName(joiner.toString());
        // 5.分区排名
        int partitionNum = getPartitionNum(url, partitionUrl, up.getName());
        if(partitionNum > 0){
            up.setPartitionRank(String.valueOf(partitionNum));
        }
        // /directory/subCate/rmyx/517
        // DyListCover-userName
        // DyListCover-hot
        // DyListCover-userName

        // 6.直播否

        // 7.直播标题
        up.setLiveHeadline(getElementsByClassForText(parse, "Title-header"));
        // 8.关注人数
        String followerNum = getFollowerNum(url, id);
        up.setAttention(followerNum);
        // 9.贵宾人数

        // 10.钻石粉丝人数

        // 11.头像地址
        up.setHeadPortrait(getElementsByClassForAttr(parse, "DyImg-content is-normal", "src"));

        return up;
    }

    private static String getFollowerNum(String url, String id) throws IOException {
        String followerNum = "";
        Document parse = Jsoup.parse(new URL(url + Constant.DOU_YU_SEARCH_PATH + id), 10000);
        String html = parse.body().toString();
        // 关注 2368.4万 | 视频 8,774
        Pattern compile = Pattern.compile(Constant.PATTERN_FOLLOWER_NUMBER);
        Matcher matcher = compile.matcher(html);
        if(matcher.find()){
            followerNum = matcher.group(1);
        }
        return followerNum;
    }

    private static int getPartitionNum(String url, String partitionPath, String name) throws IOException, JSONException {
        Document parse = Jsoup.parse(new URL(url + partitionPath), 1000);
        int num = 0;
        // https://www.douyu.com/gapi/rkc/directory/mixList/2_270/2
        String json = "{}";
        Pattern compile = Pattern.compile("(?<=DATA =)(.*?)(?=;\\n)");
        Matcher matcher = compile.matcher(parse.body().toString());
        if(matcher.find()){
            json = matcher.group(1);
        }
        JSONObject jsonObject = new JSONObject(json);
        int pageCount = jsonObject.getInt("pageCount");
        String path = jsonObject.getString("pagePath");
        path = path.substring(1, path.length());
        for (int i = 1; i <= pageCount; i++) {
            String pageJson = NetUtil.getNetFileContent(url + path + i);
            JSONArray jsonArray = new JSONArray(JSONPath.read(pageJson, "data.rl").toString());
            for (int j = 0; j < jsonArray.length(); j++) {
                String upName = JSONPath.read(pageJson, String.format("data.rl[%s].nn", j)).toString();
                if(StringUtils.equals(upName, name)){
                    num ++;
                    pageCount = i;
                    break;
                }
                num ++;
            }
        }
        return num;
    }

    private static Elements getElementsByClass(Document document, String classValue){
        Elements elementsByClass = document.getElementsByClass(classValue);
        return elementsByClass;
    }
    private static String getElementsByClassForText(Document document, String classValue){
        Elements elementsByClass = document.getElementsByClass(classValue);
        if(elementsByClass.first() == null){
            return "";
        }
        return elementsByClass.first().text();
    }

    private static String getElementsByClassForAttr(Document document, String classValue, String attr){
        Elements elementsByClass = document.getElementsByClass(classValue);
        if(elementsByClass.first() == null){
            return "";
        }
        return elementsByClass.first().attr(attr);
    }
}
